package com.ccys.cms.controller.corporateAndInsurance;


import com.ccys.cms.service.corporateAndInsurance.CDMPBenefitService;
import com.ccys.cms.service.corporateAndInsurance.CDMPService;
import com.ccys.cms.service.corporateAndInsurance.PlanBenefitSService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.corporateAndInsurance.CDMPDto;
import com.ccys.db.dto.web.productAndService.NumEnum;
import com.ccys.db.entity.TblCdmp;
import com.ccys.db.entity.TblCdmpBenefit;
import com.ccys.db.entity.TblPlan;
import com.ccys.db.rely.BaseEntity;
import com.ccys.db.vo.corporateAndInsurance.CDMPVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/corporateAndInsurance")
@Api(tags = "cdmp配套管理")
public class CDMPController {


    @Resource
    private CDMPService service;

    @Resource
    private CDMPBenefitService benefitService;

    @Resource
    private PlanBenefitSService benefitSService;


    @PostMapping("cdmp")
    @ApiOperation("新增")
    @Transactional
    public ResponseResult insert(TblCdmp model) {

        int i = service.insertOrUpdate(model);
        return ResponseResult.update(i);
    }

    @PutMapping("cdmp")
    @ApiOperation("修改")
    @Transactional
    public ResponseResult update(TblCdmp model) {

        int i = service.insertOrUpdate(model);
        return ResponseResult.update(i);
    }


    @GetMapping("cdmp/detail")
    @ApiOperation("根据id查询")
    public ResponseResult<TblPlan, Object> getById(String id) {

        return ResponseResult.success(service.findEntityById(id));
    }


    @DeleteMapping("cdmp")
    @ApiOperation("根据Id删除")
    @Transactional
    public ResponseResult delete(String id) {

        TblCdmp model = new TblCdmp();
        model.setId(id);
        model.setDelFlag(NumEnum.DEL.getCode());
        int i = service.updateEntityById(model);
        // 删除其他关联的东西
        List<TblCdmpBenefit> benefitList = benefitService.findListByLimit(TblCdmpBenefit.class, new ArrayList<String>() {{
            add("del_flag = 0");
            add(" plan_id = '" + id + "'");
        }}, "created_on desc");
        // 删除benefit
        benefitService.deleteBenefit(id);
        // 删除benefitService
        List<String> benefitIds = benefitList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        benefitSService.deleteBenefitServiceByBenefitIds(benefitIds);
        return ResponseResult.update(i);
    }


    @GetMapping("cdmp")
    @ApiOperation(value = "查询分页", notes = "排序字段 t1.name / t1.status /t2. user_fullname / t1.created_on ")
    public ResponseResult<PageInfo<CDMPVo>, Object> getPage(CDMPDto dto) {
        return service.getPage(dto);
    }
}
